import {
	ref,
	computed,
	watchEffect
} from 'vue'
import {
	useRouter
} from 'vue-router'
import {
	$fetch
} from 'ofetch'
import {
	useToken
} from './useToken'
import {
	baseURL
} from '@/composables/useFetchApi'

// ✅ 全局响应式状态（核心）
const isAuthenticated = ref(false)
const userInfo = ref(null)

export const useAuth = () => {
	const {
		getToken,
		setToken,
		clearToken
	} = useToken()
	const router = process.client ? useRouter() : null
	const API_BASE = baseURL

	// ✅ 根据 token 初始化状态
	if (process.client) {
		const token = getToken()
		isAuthenticated.value = !!token
		const savedUser = localStorage.getItem('userInfo')
		if (savedUser) userInfo.value = JSON.parse(savedUser)
	}

	// ✅ 手机号验证码登录
	const loginByPhone = async (credentials) => {
		const res = await $fetch(`${API_BASE}/api/login`, {
			method: 'POST',
			body: credentials
		})
		if (res.code === 200) {
			setToken(res.data.access_token)
			localStorage.setItem('userInfo', JSON.stringify(res.data.user))
			userInfo.value = res.data.user
			isAuthenticated.value = true
			return res
		} else {
			throw new Error(res.msg || '手机号登录失败')
		}
	}

	// ✅ 飞机号密码登录
	const loginByPassword = async (credentials) => {
		const res = await $fetch(`${API_BASE}/api/auth/login_by_password`, {
			method: 'POST',
			body: credentials
		})
		if (res.code === 200) {
			setToken(res.data.access_token)
			localStorage.setItem('userInfo', JSON.stringify(res.data.user))
			userInfo.value = res.data.user
			isAuthenticated.value = true
			return res
		} else {
			throw new Error(res.msg || '密码登录失败')
		}
	}

	// ✅ 登出
	const logout = async () => {
		try {
			await $fetch(`${API_BASE}/api/auth/logout`, {
				method: 'POST',
				headers: {
					Authorization: `Bearer ${getToken()}`
				}
			})
		} catch (e) {
			console.warn('退出时API错误', e)
		} finally {
			clearToken()
			localStorage.removeItem('userInfo')
			sessionStorage.clear()
			userInfo.value = null
			isAuthenticated.value = false
		}
	}

	// ✅ 获取用户信息（可在登录后主动刷新）
	const fetchUser = async () => {
		if (!getToken()) return null
		try {
			const res = await $fetch(`${API_BASE}/api/auth/me`, {
				headers: {
					Authorization: `Bearer ${getToken()}`
				}
			})
			if (res.code === 200) {
				userInfo.value = res.data
				localStorage.setItem('userInfo', JSON.stringify(res.data))
				return res.data
			}
		} catch (error) {
			console.error('获取用户信息失败:', error)
			logout()
			return null
		}
	}

	return {
		isAuthenticated: computed(() => isAuthenticated.value),
		userInfo,
		loginByPhone,
		loginByPassword,
		logout,
		fetchUser
	}
}